﻿using System;
using System.Text;

namespace System
{
    public static class StringHelper
    {
        public static string SubstringEx(this string str, int start, int count = -1)
        {
            try
            {
                if (str != null && start > str.Length) return string.Empty;
                if (count > 0)
                    return str.Substring(start, count);
                return str.Substring(start);
            }
            catch (Exception ex)
            {

            }
            return string.Empty;
        }

        public static string ToBase64Str(this string str)
        {
            var bts = Encoding.UTF8.GetBytes(str);
            return Convert.ToBase64String(bts);
        }

        public static string FromBase64Str(this string str)
        {
            var bts = Convert.FromBase64String(str);
            return Encoding.UTF8.GetString(bts);
        }

        /// <summary> 
        /// unicode转中文 
        /// </summary> 
        /// <returns></returns> 
        public static string UnicodeToString(this string str)
        {
            string outStr = "";
            try
            {
                if (!string.IsNullOrEmpty(str))
                {
                    string[] ls = str.Split(new string[] { "\\u" }, StringSplitOptions.RemoveEmptyEntries);
                    StringBuilder builder = new StringBuilder();
                    int len = ls.Length;
                    for (int i = 0; i < len; i++)
                    {
                        //builder.Append((Char)ushort.Parse(ls[i], System.Globalization.NumberStyles.HexNumber));
                        builder.Append(Convert.ToChar(ushort.Parse(ls[i], System.Globalization.NumberStyles.HexNumber)));
                    }
                    outStr = builder.ToString();
                }
            }
            catch (Exception)
            {
                outStr = str;
            }
            return outStr;
        }
    }
}
